package com.wyu.blog.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wyu.blog.dto.RespDTO;
import com.wyu.blog.entity.*;
import com.wyu.blog.service.*;
import com.wyu.blog.util.Markdown2HtmlUtil;
import com.wyu.blog.util.RecommendUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ArticleController {

    @Autowired
    private SortService sortService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private CollectService collectService;

    @Autowired
    private CommentLikeService commentLikeService;

    @Autowired
    private UserFriendService userFriendService;

    /**
     * 写文章
     */
    @RequestMapping(value = "/write")
    public String write(Model model){
        List<Sort> sortList = sortService.findAllSort();
        model.addAttribute("sortList", sortList);
        model.addAttribute("article", new Article());
        return "write";
    }

    /**
     * 保存文章
     */
    @PostMapping(value = "/article/save")
    @ResponseBody
    @Transactional
    public RespDTO save(@RequestBody Article article) {

        //设置摘要,取前60个字
        if(article.getArticleContent().length() > 60) {
            article.setArticleSummary(article.getArticleContent().substring(0, 60) + "...");
        }else {
            article.setArticleSummary(article.getArticleContent() + "...");
        }
        article.setArticleDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        articleService.saveArticle(article);
        return RespDTO.ok("发布成功");
    }

    /**
     * 文章修改
     */
    @PutMapping(value = "/article/update")
    @ResponseBody
    public RespDTO updateArticleById(@RequestBody Article article){
        articleService.updateArticle(article);
        return RespDTO.ok("修改成功");
    }

    /**
     * 找到推荐文章的标题
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<Article> recommend1(User user){

        ArrayList list = new ArrayList();
        List<Collect> collArticle = collectService.findCollectByUserId(user.getUserId());
        List<Collect> notCollArticle = collectService.findNotCollect(user.getUserId());
        ArrayList notCollList = new ArrayList();
        ArrayList collList = new ArrayList();

        for(Collect collect : collArticle){
            collList.add(collect.getArticle().getArticleTitle());
        }
        for(Collect notCollect : notCollArticle) {
            notCollList.add(notCollect.getArticle().getArticleTitle());
        }
        for(int i = 0; i < collList.size(); i++){
            for(int j = 0; j < notCollList.size(); j++) {
                Map tempMap = new HashMap();
                float n = RecommendUtil.levenshtein(collList.get(i).toString(), notCollList.get(j).toString());
                tempMap.put("name",notCollList.get(j));
                tempMap.put("number",n);
                list.add(tempMap);
            }
        }

        Collections.sort(list, new Comparator<Map<String, Object>>(){

            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Float num1 =(Float)o1.get("number");//name1是从你list里面拿出来的一个
                Float num2= (Float)o2.get("number"); //name1是从你list里面拿出来的第二个name
                return -num1.compareTo(num2);
            }

        });

        List newList = list.subList(0,5);
        List nameList = new ArrayList();
        List<Article> recommendArticle = new ArrayList<>();
        for(int i = 0;i < newList.size();i++)
        {
            Map<String,Object> maps = (Map<String, Object>) newList.get(i);
            String name = maps.get("name").toString();
            int a = 2;
            nameList.add(name);
            Article article = articleService.findArticleByTitle(name);
            recommendArticle.add(article);

        }

        return recommendArticle;
    }

    /**
     * 显示文章(转为html样式)
     * @param id
     * @return
     */
    @GetMapping("article/detail/{id}")
    public String getArticleById(@PathVariable Integer id, Model model, HttpSession session,
                                 @RequestParam(defaultValue = "1",value = "pageNum") Integer pageNum) {
        User user = (User)session.getAttribute("loginUser");
        Article article = articleService.findArticleById(id);
        article.setArticleSummary(Markdown2HtmlUtil.markdown2html(article.getArticleSummary()));
        article.setArticleContent(Markdown2HtmlUtil.markdown2html(article.getArticleContent()));
        List<Article> hotArticle = articleService.findHotArticle();
        List<Article> recentArticle = articleService.findRecentArticle();
        Integer concernNum = userFriendService.findConcernNum(article.getUserId());
        Integer fansNum = userFriendService.findFansNum(article.getUserId());
        Integer articleNum = articleService.findArticleNum(article.getUserId());
        Integer collectNum = collectService.findCollectNumById(article.getUserId());
        Integer commentNum = commentService.findCommentNum(article.getArticleId());
        if(user != null) {
            List<Collect> collArticle = collectService.findCollectByUserId(user.getUserId());
            if(!collArticle.isEmpty()) {
                List<Article> recommendArticle = recommend1(user);
                model.addAttribute("recommendArticle", recommendArticle);
            }else{
                model.addAttribute("recommendArticle", null);
            }
        }
//        Integer childCommentNum = commentService.findChildCommentNum(id);

        PageHelper.startPage(pageNum,5);
        List<Comment> commentList = commentService.findCommentByArticleId2(id);
        PageInfo<Comment> commentInfo = new PageInfo<>(commentList);

        User userSession = (User)session.getAttribute("loginUser");
        List<Collect> collectList;
        boolean b = false;
        if(userSession != null) {
            collectList = collectService.findCollectByUserId(userSession.getUserId());
            for (Collect collect : collectList) {
                if (collect.getArticleId().equals(article.getArticleId())) {
                    b = true;
                }
            }
        }

        boolean c = false;
        if(userSession != null) {
            List<UserFriend> concernSession = userFriendService.findUserConcern(userSession.getUserId());
            for (UserFriend userFriend : concernSession) {
                if (userFriend.getUser().getUserName().equals(article.getUser().getUserName())) {
                    c = true;
                }
            }
        }

        HashMap<String, Integer> map = new HashMap<>();
        if(userSession != null) {
            map.put("userId", userSession.getUserId());
        }
        map.put("articleId",id);
        List<CommentLike> commentLikes = commentLikeService.findCommentLike(map);
        List<CommentLike> commentNotLikes = commentLikeService.findCommentNotLike(map);

        model.addAttribute("concernNumber",concernNum);
        model.addAttribute("fansNumber",fansNum);
        model.addAttribute("articleNumber",articleNum);
        model.addAttribute("collectNumber",collectNum);
        model.addAttribute("commentNumber",commentNum);
        model.addAttribute("hotArticle",hotArticle);
        model.addAttribute("recentArticle",recentArticle);
        model.addAttribute("article",article);
        model.addAttribute("commentList",commentList);
        model.addAttribute("commentInfo",commentInfo);
        model.addAttribute("b",b);
        model.addAttribute("c",c);
        model.addAttribute("commentLikes",commentLikes);
        model.addAttribute("commentNotLikes",commentNotLikes);
        return "article";
    }

    /**
     * 评论文章
     * @param comment
     * @param request
     * @return
     */
    @PostMapping(value = "/comment")
    @ResponseBody
    public RespDTO addComment(@RequestBody Comment comment, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("loginUser");
        comment.setUserId(user.getUserId());
        comment.setCommentDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        commentService.addComment(comment);
        Article article = articleService.findArticleById(comment.getArticleId());
        article.setArticleCommentCount(article.getArticleCommentCount() + 1);
        articleService.updateComment(article);
        return RespDTO.ok("评论成功");
    }

    /**
     * 评论文章的评论(子评论)
     * @param comment
     * @param request
     * @return
     */
    @PostMapping(value = "/child/comment")
    @ResponseBody
    public RespDTO addChildComment(@RequestBody Comment comment, HttpServletRequest request){
        User user = (User) request.getSession().getAttribute("loginUser");
        comment.setCommentDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        comment.setUserId(user.getUserId());
        commentService.addChildComment(comment);
        Article article = articleService.findArticleById(comment.getArticleId());
        article.setArticleCommentCount(article.getArticleCommentCount() + 1);
        articleService.updateComment(article);
        Comment parentComment = commentService.findComment(comment.getParentCommentId());
        parentComment.setChildCommentCount(parentComment.getChildCommentCount() + 1);
        commentService.updateChildComment(parentComment);
        return RespDTO.ok("评论成功");
    }


    /**
     * 得到评论的子评论
     * @param commentId
     * @return
     */
    @GetMapping(value = "/childComment")
    @ResponseBody
    public RespDTO getChildComments(@Param("commentId") Integer commentId){
        List<Comment> childComments = commentService.findChildComments(commentId);
        return RespDTO.ok("二级评论测试成功",childComments);
    }

    /**
     * 文章收藏
     */
    @PostMapping(value = "/article/collect")
    @ResponseBody
    public RespDTO addArticleCollect(@RequestBody Collect collect){
        collectService.addCollect(collect);
        Article article = articleService.findArticleById(collect.getArticleId());
        article.setArticleLikeCount(article.getArticleLikeCount() + 1);
        articleService.updateCollect(article);
        return RespDTO.ok("收藏成功");
    }

    /**
     * 取消文章收藏
     */
    @DeleteMapping(value = "/article/cancelCollect/{userId}/{articleId}")
    @ResponseBody
    public RespDTO cancelArticleCollect(@PathVariable("userId") Integer userId,
                                        @PathVariable("articleId") Integer articleId){
        HashMap<String,Integer> map = new HashMap<>();
        map.put("userId",userId);
        map.put("articleId",articleId);
        collectService.deleteCollect(map);
        Article article = articleService.findArticleById(articleId);
        article.setArticleLikeCount(article.getArticleLikeCount() - 1);
        articleService.updateCollect(article);
        return RespDTO.ok("取消收藏成功");
    }

    /**
     * 评论点赞
     */
    @PostMapping(value = "/comment/like")
    @ResponseBody
    public RespDTO addCommentLike(@RequestBody CommentLike commentLike){
        commentLikeService.addLike(commentLike);
        Comment comment = commentService.findComment(commentLike.getCommentId());
        comment.setCommentLikeCount(comment.getCommentLikeCount() + 1);
        commentService.updateLike(comment);
        return RespDTO.ok("点赞成功");
    }

    /**
     * 取消文章点赞
     */
    @DeleteMapping(value = "/comment/cancelLike/{userId}/{commentId}")
    @ResponseBody
    public RespDTO cancelCommentLike(@PathVariable("userId") Integer userId,
                                        @PathVariable("commentId") Integer commentId){
        HashMap<String,Integer> map = new HashMap<>();
        map.put("userId",userId);
        map.put("commentId",commentId);
        commentLikeService.deleteLike(map);
        Comment comment = commentService.findComment(commentId);
        comment.setCommentLikeCount(comment.getCommentLikeCount() - 1);
        commentService.updateLike(comment);
        return RespDTO.ok("取消点赞成功");
    }


}
